/** Copyright (C) 2007 Pascal Richter
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package jlfm.lastfm.tools.id3;

import java.io.File;

import jlfm.lastfm.client.LastFmClientFaultException;

import org.blinkenlights.jid3.ID3Exception;
import org.blinkenlights.jid3.MP3File;
import org.blinkenlights.jid3.MediaFile;
import org.blinkenlights.jid3.v1.ID3V1_1Tag;
import org.blinkenlights.jid3.v2.ID3V2_3_0Tag;

public class ID3Tagger {

	public static void tag(File mp3File, ID3Metadata metadata)
			throws LastFmClientFaultException {
		try {
			MediaFile oMediaFile = new MP3File(mp3File);

			ID3V2_3_0Tag tag2_3 = new ID3V2_3_0Tag();
			if (metadata.getAlbumTitle() != null) {
				tag2_3.setAlbum(metadata.getAlbumTitle());
			}
			if (metadata.getArtistName() != null) {
				tag2_3.setArtist(metadata.getArtistName());
			}
			if (metadata.getTrackTitle() != null) {
				tag2_3.setTitle(metadata.getTrackTitle());
			}
			if (metadata.getTrackNumber() != -1) {
				tag2_3.setTrackNumber(metadata.getTrackNumber());
			}
			if (metadata.getYearOfRelease() != -1) {
				tag2_3.setYear(metadata.getYearOfRelease());
			}

			tag2_3.setComment("Downloaded from LastFM via jlfm v0.3");

			ID3V1_1Tag tag1_1 = new ID3V1_1Tag();
			if (metadata.getAlbumTitle() != null) {
				tag1_1.setAlbum(metadata.getAlbumTitle());
			}
			if (metadata.getArtistName() != null) {
				tag1_1.setArtist(metadata.getArtistName());
			}
			if (metadata.getTrackTitle() != null) {
				tag1_1.setTitle(metadata.getTrackTitle());
			}
			if (metadata.getTrackNumber() != -1) {
				tag1_1.setAlbumTrack(metadata.getTrackNumber());
			}
			if (metadata.getYearOfRelease() != -1) {
				tag1_1.setYear(Integer.valueOf(metadata.getYearOfRelease())
						.toString());
			}

			tag1_1.setComment("Downloaded from LastFM via jlfm v0.3");

			oMediaFile.setID3Tag(tag2_3);
			oMediaFile.setID3Tag(tag1_1);
			oMediaFile.sync();
		} catch (ID3Exception e) {
			throw new LastFmClientFaultException(e);
		}
	}
}
